﻿using System;
using System.IO;

namespace SelArom.Net.Sitefinity.Pages
{
	/// <summary>
	/// Intermediary PageBase between Telerik.Cms.Web.InternalPage and /sitefinity/cmsentrypoint.aspx to detect if user is on a mobile device. If mobile, switches to mobile them.
	/// REQUIRES:
	/// /App_Master/Mobile.master
	/// /App_Themes/Mobile
	/// </summary>
	public class DetectingPage : Telerik.Cms.Web.InternalPage
	{
		protected override void OnPreInit(EventArgs e)
		{
			if (e != null)
				base.OnPreInit(e);

			// check for mobile site
			if (Session["mobile"] == null || !((bool)Session["mobile"])) return;

			// create mobile theme if necessary, set as current theme
			var themePath = Server.MapPath("~/App_Themes/Mobile");
			if (!Directory.Exists(themePath)) Directory.CreateDirectory(themePath);
			Page.Theme = "Mobile";

			// verify mobile master exists, skip if missing
			var mpPath = Server.MapPath("~/App_Master/Mobile.master");
			if (!File.Exists(mpPath)) return;

			// set mobile master page
			Page.MasterPageFile = "/App_Master/Mobile.master";
		}
	}
}